package cn.com.smart.module.tool.fileList.service.serviceImpl;

import cn.com.smart.framework.config.SysConfig;
import cn.com.smart.module.tool.fileList.domain.fileList;
import cn.com.smart.module.tool.fileList.mapper.fileListMapper;
import cn.com.smart.module.tool.fileList.service.fileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class fileServiceImpl implements fileService {

    @Autowired
    private fileListMapper fileListMapper;


    /**
     * 获取文件列表
     * @return
     */
    @Override
    public List<fileList> getFileList() {
        return fileListMapper.getFileList();
    }

    /**
     * 增加
     * @param fileList
     */
    @Override
    public void addFileList(fileList fileList) {
        fileListMapper.addFileList(fileList);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public int deleteFile(String id) {

        int c=0;
        boolean exits= false;
        String [] stringids = id.split(",");
        List <Long> longids=new ArrayList<>();
        
        /*string变为long*/
        for (String stringid : stringids){
            Long b=Long.parseLong(stringid);
            longids.add(b);
        }

        for (Long longid : longids){
            fileList fileList=fileListMapper.selectFileById(longid);

            /*删除本地文件*/
            try {
                File file=new File(SysConfig.getAvatarPath()+fileList.getRoute());

                if (file.exists()){
                    exits=file.delete();
                }
                if (exits) {
                    System.out.println("删除文件成功");
                } else {
                    throw new RuntimeException();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            /*删除数据库记录*/
            fileListMapper.deleteFile(longid);
            c++;
        }

        return c;

    }

}
